﻿function Get-TSMClientScheduleAssociation {    
    <#
        .SYNOPSIS
            Get TSM client schedule associations
                    
        .DESCRIPTION
            The Get-TSMClientScheduleAssociation returns client schedule associations
                    
        .PARAMETER Domain
            The domain to search

        .PARAMETER Schedule
            The schedule to search

        .PARAMETER Node
            The node to search

        .PARAMETER Rollup
            Roll up query results into individual schedule association objects

        .EXAMPLE
            Get-TSMClientScheduleAssociation

        .NOTES
            Contributors:  David Seibel
            Last Revision Date: 09/01/2015

    #>
    [CmdletBinding()]
    Param(
        [Parameter(Position = 0)]
        $Domain,
        
        [Parameter(Position = 1)]
        $Schedule,
        
        [Parameter(Position = 2)]
        $Node,

        [switch]$Rollup
    )   
    
    $whereProps = @()
    $whereProps += [PSCustomObject]@{ "Column" = "DOMAIN_NAME";   "Operator" = "LIKE"; "Value" = $Domain }
    $whereProps += [PSCustomObject]@{ "Column" = "SCHEDULE_NAME"; "Operator" = "LIKE"; "Value" = $Schedule }
    $whereProps += [PSCustomObject]@{ "Column" = "NODE_NAME";     "Operator" = "LIKE"; "Value" = $Node }

    $query = Format-TSMQuery -Table "ASSOCIATIONS" -Where $whereProps -OrderBy "DOMAIN_NAME,SCHEDULE_NAME,NODE_NAME"
    $result = Invoke-TSMCommand -Command $query
    
    $defaultDisplaySet = 'DOMAIN_NAME','SCHEDULE_NAME','NODE_NAME'
    $typeDefinitions = @{
                        "CHG_TIME" = [DateTime]
                        }
    
    $results = Format-TSMData -Data $result -TypeDefinitions $typeDefinitions -DefaultDisplaySet $defaultDisplaySet

    if ($Rollup) {
        $finalResults = @()
        foreach ($grouping in ($results | Group-Object -Property SCHEDULE_NAME)) {
            $temp = New-Object PSObject
            $temp | Add-Member -MemberType NoteProperty -Name "SCHEDULE_NAME" -Value $grouping.Name
            $temp | Add-Member -MemberType NoteProperty -Name "DOMAIN_NAME  " -Value ($grouping.Group | Select-Object -First 1).DOMAIN_NAME
            $temp | Add-Member -MemberType NoteProperty -Name "NODES"         -Value (($grouping.Group).NODE_NAME)
            $finalResults += $temp
        }
    } else {
        $finalResults = $results
    }

    return $finalResults
}